/*!
 * \file ctp_factory.hpp
 * \project AI_CTP
 * 
 * \brief CTP工厂管理器
 *        提供工厂级别的API实例管理，支持多账户、多策略、连接池等企业级功能
 */
#pragma once

#include "ctp_common.hpp"
#include "md_api.hpp"
#include "trader_api.hpp"
#include "performance/lock_free_queue.hpp"
#include "performance/memory_pool.hpp"

#include <memory>
#include <unordered_map>
#include <string>
#include <mutex>
#include <shared_mutex>
#include <thread>
#include <atomic>
#include <vector>
#include <functional>
#include <chrono>

namespace ctp_api {
namespace factory {

// 连接池状态监控
struct ConnectionStats {
    std::string account_id;
    std::string connection_type; // "md" or "trader"
    ConnectionState state;
    std::chrono::steady_clock::time_point last_heartbeat;
    uint64_t total_messages = 0;
    uint64_t error_count = 0;
    double latency_ms = 0.0;
};

// 高性能数据处理器
template<typename DataType>
class HighPerformanceDataProcessor {
private:
    using Queue = performance::SPSCQueue<DataType, 16384>;
    using Pool = performance::CtpDataPool<DataType>;
    
    std::unique_ptr<Queue> queue_;
    Pool& pool_;
    std::thread worker_thread_;
    std::atomic<bool> running_{false};
    std::function<void(const DataType&)> handler_;
    
    void process_loop() {
        DataType item;
        while (running_.load(std::memory_order_acquire)) {
            if (queue_->try_pop(item)) {
                if (handler_) {
                    handler_(item);
                }
            } else {
                // 短暂休眠，避免CPU过度占用
                std::this_thread::sleep_for(std::chrono::microseconds(1));
            }
        }
    }
    
public:
    explicit HighPerformanceDataProcessor(std::function<void(const DataType&)> handler)
        : queue_(std::make_unique<Queue>())
        , pool_(performance::MemoryPoolManager::getInstance().getPool<DataType>())
        , handler_(std::move(handler)) {}
    
    ~HighPerformanceDataProcessor() {
        stop();
    }
    
    void start() {
        if (!running_.exchange(true)) {
            worker_thread_ = std::thread(&HighPerformanceDataProcessor::process_loop, this);
        }
    }
    
    void stop() {
        if (running_.exchange(false)) {
            if (worker_thread_.joinable()) {
                worker_thread_.join();
            }
        }
    }
    
    bool push_data(const DataType& data) {
        return queue_->try_push(data);
    }
    
    bool push_data(DataType&& data) {
        return queue_->try_push(std::move(data));
    }
    
    double get_utilization() const {
        return queue_->utilization();
    }
};

// 高性能行情回调处理器
class HighPerformanceMdCallback : public MdSpiCallback {
private:
    std::unique_ptr<HighPerformanceDataProcessor<DepthMarketData>> md_processor_;
    std::unique_ptr<HighPerformanceDataProcessor<ErrorInfo>> error_processor_;
    std::function<void(const DepthMarketData&)> md_handler_;
    std::function<void(const ErrorInfo&)> error_handler_;
    
public:
    explicit HighPerformanceMdCallback(
        std::function<void(const DepthMarketData&)> md_handler = nullptr,
        std::function<void(const ErrorInfo&)> error_handler = nullptr)
        : md_handler_(std::move(md_handler))
        , error_handler_(std::move(error_handler)) {
        
        if (md_handler_) {
            md_processor_ = std::make_unique<HighPerformanceDataProcessor<DepthMarketData>>(md_handler_);
            md_processor_->start();
        }
        
        if (error_handler_) {
            error_processor_ = std::make_unique<HighPerformanceDataProcessor<ErrorInfo>>(error_handler_);
            error_processor_->start();
        }
    }
    
    ~HighPerformanceMdCallback() = default;
    
    void on_rtn_depth_market_data(const DepthMarketData& market_data) override {
        if (md_processor_) {
            if (!md_processor_->push_data(market_data)) {
                // 队列满，记录警告
                // TODO: 添加日志系统
            }
        }
    }
    
    void on_rsp_error(const ErrorInfo& error_info, int request_id, bool is_last) override {
        if (error_processor_) {
            error_processor_->push_data(error_info);
        }
    }
    
    // 获取性能统计
    struct ProcessorStats {
        double md_queue_utilization = 0.0;
        double error_queue_utilization = 0.0;
    };
    
    ProcessorStats get_stats() const {
        ProcessorStats stats;
        if (md_processor_) {
            stats.md_queue_utilization = md_processor_->get_utilization();
        }
        if (error_processor_) {
            stats.error_queue_utilization = error_processor_->get_utilization();
        }
        return stats;
    }
};

// CTP连接管理器
class CtpConnectionManager {
private:
    struct ConnectionInstance {
        std::string account_id;
        CtpConfig config;
        std::unique_ptr<MdApi> md_api;
        std::unique_ptr<TraderApi> trader_api;
        std::shared_ptr<HighPerformanceMdCallback> md_callback;
        std::shared_ptr<TraderSpiCallback> trader_callback;
        ConnectionStats md_stats;
        ConnectionStats trader_stats;
        std::chrono::steady_clock::time_point created_time;
        
        ConnectionInstance(const std::string& id, const CtpConfig& cfg) 
            : account_id(id), config(cfg), created_time(std::chrono::steady_clock::now()) {
            md_stats.account_id = id;
            md_stats.connection_type = "md";
            md_stats.state = ConnectionState::DISCONNECTED;
            
            trader_stats.account_id = id;
            trader_stats.connection_type = "trader";
            trader_stats.state = ConnectionState::DISCONNECTED;
        }
    };
    
    std::unordered_map<std::string, std::unique_ptr<ConnectionInstance>> connections_;
    mutable std::shared_mutex connections_mutex_;
    std::thread monitor_thread_;
    std::atomic<bool> monitoring_{false};
    
    void monitor_connections() {
        while (monitoring_.load()) {
            std::shared_lock<std::shared_mutex> lock(connections_mutex_);
            for (auto& [account_id, conn] : connections_) {
                // 更新连接状态统计
                if (conn->md_api) {
                    conn->md_stats.state = conn->md_api->get_connection_state();
                    conn->md_stats.last_heartbeat = std::chrono::steady_clock::now();
                }
                
                if (conn->trader_api) {
                    conn->trader_stats.state = conn->trader_api->get_connection_state();
                    conn->trader_stats.last_heartbeat = std::chrono::steady_clock::now();
                }
            }
            lock.unlock();
            
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
    }
    
public:
    CtpConnectionManager() {
        monitoring_ = true;
        monitor_thread_ = std::thread(&CtpConnectionManager::monitor_connections, this);
    }
    
    ~CtpConnectionManager() {
        monitoring_ = false;
        if (monitor_thread_.joinable()) {
            monitor_thread_.join();
        }
    }
    
    // 创建连接实例
    bool create_connection(const std::string& account_id, const CtpConfig& config) {
        std::unique_lock<std::shared_mutex> lock(connections_mutex_);
        
        if (connections_.find(account_id) != connections_.end()) {
            return false; // 已存在
        }
        
        auto instance = std::make_unique<ConnectionInstance>(account_id, config);
        connections_[account_id] = std::move(instance);
        return true;
    }
    
    // 初始化行情连接
    bool init_market_data(const std::string& account_id,
                         std::function<void(const DepthMarketData&)> md_handler = nullptr,
                         std::function<void(const ErrorInfo&)> error_handler = nullptr) {
        std::unique_lock<std::shared_mutex> lock(connections_mutex_);
        
        auto it = connections_.find(account_id);
        if (it == connections_.end()) {
            return false;
        }
        
        auto& conn = it->second;
        if (conn->md_api) {
            return false; // 已初始化
        }
        
        conn->md_api = std::make_unique<MdApi>();
        conn->md_callback = std::make_shared<HighPerformanceMdCallback>(md_handler, error_handler);
        
        if (!conn->md_api->init()) {
            conn->md_api.reset();
            conn->md_callback.reset();
            return false;
        }
        
        conn->md_api->set_config(conn->config);
        conn->md_api->register_callback(conn->md_callback);
        conn->md_api->register_front(conn->config.md_server.front_address);
        conn->md_api->init_api();
        
        return true;
    }
    
    // 初始化交易连接
    bool init_trader(const std::string& account_id,
                    std::shared_ptr<TraderSpiCallback> callback = nullptr) {
        std::unique_lock<std::shared_mutex> lock(connections_mutex_);
        
        auto it = connections_.find(account_id);
        if (it == connections_.end()) {
            return false;
        }
        
        auto& conn = it->second;
        if (conn->trader_api) {
            return false; // 已初始化
        }
        
        conn->trader_api = std::make_unique<TraderApi>();
        conn->trader_callback = callback;
        
        if (!conn->trader_api->init()) {
            conn->trader_api.reset();
            return false;
        }
        
        conn->trader_api->set_config(conn->config);
        if (callback) {
            conn->trader_api->register_callback(callback);
        }
        conn->trader_api->register_front(conn->config.trader_server.front_address);
        conn->trader_api->init_api();
        
        return true;
    }
    
    // 获取行情API
    MdApi* get_md_api(const std::string& account_id) {
        std::shared_lock<std::shared_mutex> lock(connections_mutex_);
        auto it = connections_.find(account_id);
        return (it != connections_.end()) ? it->second->md_api.get() : nullptr;
    }
    
    // 获取交易API
    TraderApi* get_trader_api(const std::string& account_id) {
        std::shared_lock<std::shared_mutex> lock(connections_mutex_);
        auto it = connections_.find(account_id);
        return (it != connections_.end()) ? it->second->trader_api.get() : nullptr;
    }
    
    // 获取连接统计
    std::vector<ConnectionStats> get_all_stats() const {
        std::shared_lock<std::shared_mutex> lock(connections_mutex_);
        std::vector<ConnectionStats> result;
        
        for (const auto& [account_id, conn] : connections_) {
            result.push_back(conn->md_stats);
            result.push_back(conn->trader_stats);
        }
        
        return result;
    }
    
    // 移除连接
    bool remove_connection(const std::string& account_id) {
        std::unique_lock<std::shared_mutex> lock(connections_mutex_);
        return connections_.erase(account_id) > 0;
    }
    
    // 获取所有账户ID
    std::vector<std::string> get_account_ids() const {
        std::shared_lock<std::shared_mutex> lock(connections_mutex_);
        std::vector<std::string> result;
        for (const auto& [account_id, conn] : connections_) {
            result.push_back(account_id);
        }
        return result;
    }
};

// CTP工厂主类
class CtpFactory {
private:
    static std::unique_ptr<CtpFactory> instance_;
    static std::once_flag init_flag_;
    
    std::unique_ptr<CtpConnectionManager> connection_manager_;
    
    CtpFactory() : connection_manager_(std::make_unique<CtpConnectionManager>()) {}
    
public:
    static CtpFactory& getInstance() {
        std::call_once(init_flag_, []() {
            instance_ = std::unique_ptr<CtpFactory>(new CtpFactory());
        });
        return *instance_;
    }
    
    // 从配置文件创建连接
    bool create_connection_from_config(const std::string& account_id, 
                                      const std::string& config_file = "config.json") {
        try {
            CtpConfig config = CtpConfig::load_from_file(config_file);
            return connection_manager_->create_connection(account_id, config);
        } catch (const std::exception& e) {
            return false;
        }
    }
    
    // 从配置对象创建连接
    bool create_connection(const std::string& account_id, const CtpConfig& config) {
        return connection_manager_->create_connection(account_id, config);
    }
    
    // 创建高性能行情连接
    bool create_high_performance_md(const std::string& account_id,
                                   std::function<void(const DepthMarketData&)> md_handler = nullptr,
                                   std::function<void(const ErrorInfo&)> error_handler = nullptr) {
        return connection_manager_->init_market_data(account_id, md_handler, error_handler);
    }
    
    // 创建交易连接
    bool create_trader(const std::string& account_id,
                      std::shared_ptr<TraderSpiCallback> trader_handler = nullptr) {
        if (account_id.empty()) {
            return false;
        }
        
        auto it = connection_manager_->connections_.find(account_id);
        if (it == connection_manager_->connections_.end()) {
            return false;  // 连接不存在
        }
        
        return connection_manager_->init_trader(account_id, trader_handler);
    }
    
    // 获取API实例
    MdApi* get_md_api(const std::string& account_id) {
        return connection_manager_->get_md_api(account_id);
    }
    
    TraderApi* get_trader_api(const std::string& account_id) {
        return connection_manager_->get_trader_api(account_id);
    }
    
    // 批量登录多个账户
    bool batch_login(const std::vector<std::string>& account_ids) {
        if (account_ids.empty()) {
            return false;
        }
        
        bool all_success = true;
        std::vector<std::thread> login_threads;
        std::mutex result_mutex;
        
        for (const auto& account_id : account_ids) {
            login_threads.emplace_back([this, account_id, &all_success, &result_mutex]() {
                try {
                    // 这里应该调用具体的登录逻辑
                    // 由于时间关系，暂时简化实现
                    std::this_thread::sleep_for(std::chrono::milliseconds(100));
                    
                    std::lock_guard<std::mutex> lock(result_mutex);
                    // 这里应该检查实际的登录结果
                    // all_success &= login_result;
                } catch (const std::exception& e) {
                    std::lock_guard<std::mutex> lock(result_mutex);
                    all_success = false;
                }
            });
        }
        
        // 等待所有登录线程完成
        for (auto& thread : login_threads) {
            if (thread.joinable()) {
                thread.join();
            }
        }
        
        return all_success;
    }
    
    // 批量订阅行情
    bool batch_subscribe(const std::vector<std::string>& account_ids, 
                        const std::vector<std::string>& instruments) {
        if (account_ids.empty() || instruments.empty()) {
            return false;
        }
        
        bool all_success = true;
        std::vector<std::thread> subscribe_threads;
        std::mutex result_mutex;
        
        for (const auto& account_id : account_ids) {
            subscribe_threads.emplace_back([this, account_id, instruments, &all_success, &result_mutex]() {
                try {
                    // 获取对应的行情API并订阅
                    auto it = connection_manager_->connections_.find(account_id);
                    if (it != connection_manager_->connections_.end() && it->second->md_api) {
                        std::vector<char*> instrument_ptrs;
                        for (const auto& inst : instruments) {
                            instrument_ptrs.push_back(const_cast<char*>(inst.c_str()));
                        }
                        
                        // 这里应该调用实际的订阅API
                        // int result = it->second->md_api->SubscribeMarketData(instrument_ptrs.data(), instrument_ptrs.size());
                        
                        std::lock_guard<std::mutex> lock(result_mutex);
                        // all_success &= (result == 0);
                    } else {
                        std::lock_guard<std::mutex> lock(result_mutex);
                        all_success = false;
                    }
                } catch (const std::exception& e) {
                    std::lock_guard<std::mutex> lock(result_mutex);
                    all_success = false;
                }
            });
        }
        
        // 等待所有订阅线程完成
        for (auto& thread : subscribe_threads) {
            if (thread.joinable()) {
                thread.join();
            }
        }
        
        return all_success;
    }
    
    // 系统统计结构
    struct SystemStats {
        std::vector<ConnectionStats> connection_stats;
        performance::HighPerformanceAllocator::MemoryStats memory_stats;
        size_t total_connections = 0;
        size_t active_connections = 0;
    };
    
    // 获取系统统计信息
    SystemStats get_system_stats() const {
        SystemStats stats;
        
        if (connection_manager_) {
            // 获取连接统计
            stats.connection_stats = connection_manager_->get_all_stats();
            stats.total_connections = stats.connection_stats.size();
            
            // 计算活跃连接数
            for (const auto& conn_stat : stats.connection_stats) {
                if (conn_stat.state == ConnectionState::READY ||
                    conn_stat.state == ConnectionState::CONNECTED ||
                    conn_stat.state == ConnectionState::LOGGED_IN) {
                    stats.active_connections++;
                }
            }
        }
        
        // 获取内存统计
        stats.memory_stats = performance::MemoryPoolManager::getInstance().getMemoryStats();
        
        return stats;
    }
    
    // 移除连接
    bool remove_connection(const std::string& account_id) {
        return connection_manager_ ? connection_manager_->remove_connection(account_id) : false;
    }
    
    // 获取所有账户ID
    std::vector<std::string> get_all_accounts() const {
        return connection_manager_ ? connection_manager_->get_account_ids() : std::vector<std::string>();
    }
};

// 静态成员定义
std::unique_ptr<CtpFactory> CtpFactory::instance_ = nullptr;
std::once_flag CtpFactory::init_flag_;

} // namespace factory
} // namespace ctp_api 